package com.qianniu.napi.common.util;

import com.coremedia.iso.IsoFile;
import com.qianniu.napi.admin.web.BannerController;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class VideoUtil {

    private static final Logger logger = LoggerFactory.getLogger(VideoUtil.class);

    /**
     * 获取指定视频的帧并保存为图片至指定目录
     *
     * @param file      源视频文件
     * @param framefile 截取帧的图片存放路径
     * @throws Exception
     */
//    public static void fetchPic(File file, String framefile) throws Exception {
    public static JSONObject fetchPic(String file, String framefile) throws Exception {
//        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
        logger.debug("---------------------------------------VideoUtil file="+file);
        logger.debug("---------------------------------------VideoUtil framefile="+framefile);
        FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(file);
        ff.start();
        int lenght = ff.getLengthInFrames();
        File targetFile = new File(framefile);
        int i = 0;
        Frame frame = null;
        while (i < lenght) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            frame = ff.grabFrame();
            if ((i > 5) && (frame.image != null)) {
                break;
            }
            i++;
        }

        //获取后缀文件
        String imgSuffix = "jpg";
        if (framefile.indexOf('.') != -1) {
            String[] arr = framefile.split("\\.");
            if (arr.length >= 2) {
                imgSuffix = arr[1];
            }
        }

        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage srcBi = converter.getBufferedImage(frame);
        JSONObject jo = new JSONObject();
        int owidth = srcBi.getWidth();
        int oheight = srcBi.getHeight();
        jo.put("owidth",owidth);
        jo.put("oheight",oheight);
        //对截取的帧进行等比例缩放
        int width = 750;
        int height = (int) (((double) width / owidth) * oheight);
        jo.put("mheight",height);

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(srcBi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);

        try {
            logger.debug("---------------------------------------VideoUtil file to write");
            ImageIO.write(bi, imgSuffix, targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ff.stop();
        return jo;
    }

    /**
     * 获取视频时长，单位为秒
     *
     * @param file
     * @return 时长（s）
     */
    public static Long getVideoTime(File file) {
        Long times = 0L;
        try {
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
            ff.start();
            times = ff.getLengthInTime() / (1000 * 1000);
            ff.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }

    /**
     * 获取视频文件的播放长度(mp4、mov格式)
     *
     * @param videoPath
     * @return 单位为毫秒
     */
    public static long getMp4Duration(String videoPath) throws IOException {
        IsoFile isoFile = new IsoFile(videoPath);
        long lengthInSeconds =
                isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
                        isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
        return lengthInSeconds;
    }

    /**
     * 得到语音或视频文件时长,单位秒
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static long getDuration(String filePath) throws IOException {
        String format = getVideoFormat(filePath);
        long result = 0;
        if ("wav".equals(format)) {
            result = AudioUtil.getDuration(filePath).intValue();
        } else if ("mp3".equals(format)) {
            result = AudioUtil.getMp3Duration(filePath).intValue();
        } else if ("m4a".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        } else if ("mov".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        } else if ("mp4".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        }

        return result;
    }

    /**
     * 得到语音或视频文件时长,单位秒
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static long getDuration(String filePath, String format) throws IOException {
        long result = 0;
        if ("wav".equals(format)) {
            result = AudioUtil.getDuration(filePath).intValue();
        } else if ("mp3".equals(format)) {
            result = AudioUtil.getMp3Duration(filePath).intValue();
        } else if ("m4a".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        } else if ("mov".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        } else if ("mp4".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        }

        return result;
    }

    /**
     * 得到文件格式
     *
     * @param path
     * @return
     */
    public static String getVideoFormat(String path) {
        return path.toLowerCase().substring(path.toLowerCase().lastIndexOf(".") + 1);
    }

}
